package com.xxkj.drugtraceability.ui.drugscan

import android.text.Html
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.xxhis.refactor.eventbus.MessageCode
import com.xxkj.drugtraceability.R
import com.xxkj.drugtraceability.base.BaseVMActivity
import com.xxkj.drugtraceability.bean.*
import com.xxkj.drugtraceability.databinding.ActivityDrugscanBinding
import com.xxkj.drugtraceability.dialog.BlueDialog
import com.xxkj.drugtraceability.dialog.YellowDialog
import com.xxkj.drugtraceability.ext.clickN
import com.xxkj.drugtraceability.lifecycle.KtxManager
import com.xxkj.drugtraceability.scan.BarcodeType
import com.xxkj.drugtraceability.utils.showCompleteToast
import com.xxkj.drugtraceability.utils.toast
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * author: zhoujingjin
 * created on: 2024/9/10 18:19
 * description:药品追溯码采集
 */
class DrugScanActivity : BaseVMActivity() {
    private val binding by binding<ActivityDrugscanBinding>(R.layout.activity_drugscan)
    private val viewModel by viewModel<DrugScanViewModel>()
    private lateinit var drugScanAdapter: DrugScanAdapter
    private var packageModel = "药盒"
    override fun initView() {
        binding.apply {
            toolBar.title = ""
            setSupportActionBar(toolBar)
            toolBar.setNavigationOnClickListener {
                onBackPressed()
            }
            recyclerView.layoutManager = LinearLayoutManager(this@DrugScanActivity)
            drugScanAdapter = DrugScanAdapter {
                //删除要强提醒，同意才能删除
                viewModel.dataList.value?.removeAt(it)
                viewModel.dataList.postValue(viewModel.dataList.value)
            }
            recyclerView.adapter = drugScanAdapter
            tvCancel.clickN {
                YellowDialog(this@DrugScanActivity, resources.getString(R.string.cancel_all)) {
                    //清空所有追溯码
                    finish()
                }
            }
            tvClear.clickN {
                YellowDialog(this@DrugScanActivity, resources.getString(R.string.clear_all)) {
                    //清空所有追溯码
                    viewModel.clearData()
                }
            }
            tvSave.clickN {
                //调用保存接口
                var alert = false
                var noData = false
                var alertStr = ""
                if (drugScanAdapter.data.isNullOrEmpty()) {
                    noData = true
                } else {
                    if (drugScanAdapter.data.size != drugInStorageBean?.cnt?.toDouble()
                            ?.toInt()
                    ) {
                        if (drugScanAdapter.data.size < drugInStorageBean?.cnt?.toDouble()
                                ?.toInt()!!
                        ) {
                            alertStr = resources.getString(R.string.scan_not_all)
                        }
                        if (drugScanAdapter.data.size > drugInStorageBean?.cnt?.toDouble()
                                ?.toInt()!!
                        ) {
                            alertStr = "处方中扫描追溯码药品数量不一致，是否继续提交？"
                        }
                        alert = true
                    }
                }
                if (noData) {
                    //提示没有任何数据
                    YellowDialog(
                        this@DrugScanActivity,
                        resources.getString(R.string.no_data),
                        type = 1
                    ) {

                    }
                } else {
                    if (alert) {
                        BlueDialog(this@DrugScanActivity, alertStr) {
                            //保存数据
                            drugInStorageBean?.let {
                                it.dataForm = "02"
                                it.drugtracinfo = drugScanAdapter.data
                                val list = mutableListOf<DrugInStorageBean>()
                                list.add(it)
                                val drugStorageUpRequest = DrugStorageUpRequest(list)
                                viewModel.drugInStorage(Gson().toJson(drugStorageUpRequest))
                            }
                        }
                    } else {
                        //保存数据
                        drugInStorageBean?.let {
                            it.dataForm = "02"
                            it.drugtracinfo = drugScanAdapter.data
                            val list = mutableListOf<DrugInStorageBean>()
                            list.add(it)
                            val drugStorageUpRequest = DrugStorageUpRequest(list)
                            viewModel.drugInStorage(Gson().toJson(drugStorageUpRequest))
                        }
                    }
                }
            }
        }
    }

    private var drugInStorageBean: DrugInStorageBean? = null
    override fun initData() {
        val data = intent.getStringExtra("data")
        viewModel.hasData = false
        drugInStorageBean = Gson().fromJson(data, DrugInStorageBean::class.java)
        drugInStorageBean?.let {
            if (it.drugtracinfo != null && it.drugtracinfo!!.isNotEmpty()) {
                viewModel.hasData = true
                viewModel.data.addAll(it.drugtracinfo!!)
            }
            viewModel.dataList.postValue(it.drugtracinfo as MutableList<String>?)
            binding.apply {
                tvContent.text = it.drugName
                tvDetail.text =
                    "${it.drugSpec ?: ""}/${it.drugUnit}   ${it.cnt}${it.drugUnit ?: ""}"
                setCountInfo(tvCountInfo, it)
            }
        }

        if (viewModel.hasData) {
            binding.llBottom.visibility = View.GONE
            binding.llTop.visibility = View.GONE
        }
        if (!viewModel.hasData)
            viewModel.isOpenMsfx()
        drugScanAdapter.setState(viewModel.hasData)
    }

    private fun setCountInfo(tvCountInfo: TextView, drugInStorageBean: DrugInStorageBean) {
        val buffer1 = StringBuffer()
        buffer1.append("<font color='#33333F'>")
        buffer1.append("已扫/未扫：")
        buffer1.append("</font>")
        buffer1.append("<font color='#42C697'>")
        if (viewModel.dataList.value.isNullOrEmpty())
            buffer1.append(0)
        else buffer1.append(viewModel.dataList.value!!.size)
        buffer1.append("</font>")
        buffer1.append("<font color='#494953'>")
        buffer1.append("/")
        buffer1.append("</font>")
        buffer1.append("<font color='#F7745C'>")
        if (viewModel.dataList.value.isNullOrEmpty())
            buffer1.append(drugInStorageBean.cnt)
        else {
            if (drugInStorageBean.cnt <= viewModel.dataList.value!!.size) {
                buffer1.append(0)
            } else {
                buffer1.append(drugInStorageBean.cnt - viewModel.dataList.value!!.size)
            }
        }
        buffer1.append("</font>")
        tvCountInfo.text = Html.fromHtml(buffer1.toString())
    }

    private fun setCountInfo(tvCountInfo: TextView, drugInStorageBean: DrugOutStorageBean) {
        val buffer1 = StringBuffer()
        buffer1.append("<font color='#33333F'>")
        buffer1.append("已扫/未扫：")
        buffer1.append("</font>")
        buffer1.append("<font color='#42C697'>")
        if (viewModel.dataList.value.isNullOrEmpty())
            buffer1.append(0)
        else buffer1.append(viewModel.dataList.value!!.size)
        buffer1.append("</font>")
        buffer1.append("<font color='#494953'>")
        buffer1.append("/")
        buffer1.append("</font>")
        buffer1.append("<font color='#F7745C'>")
        if (viewModel.dataList.value.isNullOrEmpty())
            buffer1.append(drugInStorageBean.cnt)
        else {
            if (drugInStorageBean.cnt <= viewModel.dataList.value!!.size) {
                buffer1.append(0)
            } else {
                buffer1.append(drugInStorageBean.cnt - viewModel.dataList.value!!.size)
            }
        }
        buffer1.append("</font>")
        tvCountInfo.text = Html.fromHtml(buffer1.toString())
    }

    override fun startObserve() {
        viewModel.dataList.observe(this, Observer {
            drugInStorageBean?.let { drugInStorageBean ->
                setCountInfo(binding.tvCountInfo, drugInStorageBean)
            }
            drugScanAdapter.setList(it)
        })
        viewModel.uiState.observe(this, Observer {
            if (it.isSuccess == true) {
                showCompleteToast(this)
                binding.recyclerView.postDelayed({
                    setResult(3333)
                    finish()
                }, 1500L)
            }
            if (it.isLoading) {
                showMyDialog(resources.getString(R.string.saveing_data))
            } else {
                dismissMyDialog()
            }
            if (!it.isError.isNullOrEmpty()) {
                BlueDialog(this, it.isError!!, type = 1) {}
            }
        })
        viewModel.isShowMsfxRadio.observe(this, {
            binding.radioGroup.visibility = View.VISIBLE
            binding.radioGroup.setOnCheckedChangeListener { group, checkId ->
                if (binding.radioChest.id == binding.radioGroup.checkedRadioButtonId)
                    packageModel = binding.radioChest.tag.toString()
            }
        })
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(message: EventMessage?) {
        message?.apply {
            //扫码拿到barcode了，去请求接口
            when (message.messageCode) {
                MessageCode.SCAN_BARCODE -> {
                    if (KtxManager.isTopActivity(this@DrugScanActivity) && !viewModel.hasData) {
                        val barcodeMessage = this.any as BarcodeMessage
                        if (barcodeMessage.type == BarcodeType.SUYUAN) {
                            if (viewModel.dataList.value?.contains(barcodeMessage.barcode) == true) {
                                toast(R.string.scan_code_has)
                            } else {
                                if (packageModel == "药箱") {
                                    viewModel.queryTracCodeByBoxCode(barcodeMessage.barcode)
                                } else {
                                    viewModel.data.add(barcodeMessage.barcode)
                                    viewModel.dataList.postValue(viewModel.data)
                                }
                            }
                        } else {
                            viewModel.queryTracCodeByBoxCode(barcodeMessage.barcode)
//                            YellowDialog(this@DrugScanActivity,resources.getString(R.string.scan_suyuan),type = 1){}
                        }

                    }
                }
            }
        }
    }

    override fun onStart() {
        super.onStart()
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}